<template>
  <div class="wrapper">
    <div class="course-info-page">
      <el-row :gutter="20">
        <el-col :sm="24" :lg="24">
          <div class="course-info-header text-success"
               style="font-size: 14px; display: flex; justify-content: space-between; align-items: center;">
            <h1>《{{ courseName }}》</h1>
            <div class="button-group">
              <!--<el-button v-if="endType === 0 || endType === 1" type="warning" @click="signDetail">签到情况</el-button>-->
              <el-button v-if="endType === 0 || endType === 1" type="warning" @click="signDetail">签到情况</el-button>
              <el-button v-if="endType === undefined" type="success" @click="openAttendanceDialog">发布考勤</el-button>
              <el-button type="danger" @click="endCourse">结束上课</el-button>
            </div>
          </div>
          <hr/>
        </el-col>
      </el-row>
    </div>

    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="用户账号" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户账号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            v-model="queryParams.nickName"
            placeholder="请输入用户昵称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            v-model="queryParams.deptName"
            placeholder="请输入部门名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">

        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['course:courseStudents:remove']"
          >批量退出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['course:courseStudents:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="courseStudentsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="用户ID" width="65" align="center" prop="userId"/>
        <el-table-column label="用户账号" align="center" prop="userName"/>
        <el-table-column label="用户昵称" align="center" prop="nickName"/>
        <el-table-column label="用户邮箱" align="center" prop="email"/>
        <el-table-column label="手机号码" align="center" prop="phonenumber"/>
        <el-table-column label="用户性别" align="center" prop="sex">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
          </template>
        </el-table-column>
        <el-table-column label="部门名称" align="center" prop="deptName"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['course:courseStudents:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['course:courseStudents:remove']"
            >退出本课程
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="attendanceForm" :model="attendanceForm" :rules="rules" label-width="80px">

          <el-form-item label="考勤类型" prop="attendanceType">
            <el-select v-model="attendanceForm.attendanceType" placeholder="请选择考勤类型">
              <el-option
                v-for="dict in dict.type.attendance_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="考勤时长" prop="attendanceTime">
            <el-select v-model="attendanceForm.attendanceTime" placeholder="请选择考勤时长">
              <el-option
                v-for="dict in dict.type.attendance_time"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addAttendence">发 布</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 签到模态框 -->
      <el-dialog :title="scanTitle" :visible.sync="scanDialogVisible" width="500px" append-to-body>
        <div class="qrcode-container">
          <vue-qr
            v-if="attendanceTypeForScan === 0"
            colorDark="#EE6779"
            colorLight="#F5E1D9"
            :text="qrCodeUrl"
            :size="200"
          ></vue-qr>
          <p class="tip-text">
            {{ attendanceTypeForScan === 0 ? '扫描二维码进行签到' : '请登录系统人脸识别签到' }}
          </p>
          <p class="tip-text">
            (已签：{{signCompleted}} / 未签：{{total-signCompleted}})
          </p>
        </div>
        <hr class="content-separator">
        <div class="attendance-info">
          <table>
            <thead>
            <tr>
              <th>学号</th>
              <th>姓名</th>
              <th>签到状态</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(record, index) in signRecordList" :key="index">
              <td>{{ record.userName }}</td>
              <td>{{ record.nickName }}</td>
              <td><dict-tag :options="dict.type.sign_status" :value="record.signStatus"/></td>
            </tr>
            </tbody>
          </table>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  endCourseRecord,
  listCourseStudents,
  getCourseStudents,
  delCourseStudents,
  addCourseStudents,
  updateCourseStudents
} from "@/api/course/startCourse";
import VueQr from "vue-qr";
import { addAttendanceRecord, getEndType } from "@/api/attendance/attendanceRecord";
import { listSignRecordForDetail,getCodeLink, getCourseRecordIdByCourseId, getAttendanceTypeByCourseId } from "@/api/attendance/signRecord";

export default {
  name: "CourseStudents",
  dicts: ['sys_user_sex', 'attendance_type', 'attendance_time', 'sign_status'],
  components: {
    VueQr
  },
  data() {
    return {
      courseId: this.$route.query.courseId, // 获取路由参数中的课程 ID
      teacherId: this.$route.query.userId,
      courseName: this.$route.query.courseName,
      // 遮罩层
      loading: true,
      // 选中数组
      userNames: [],
      nickNames: [],
      userIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程学生列表表格数据
      courseStudentsList: [],
      // 考勤信息表格数据
      signRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        nickName: null,
        deptName: null
      },
      // 表单参数
      form: {},
      attendanceForm: {},
      // 表单校验
      rules: {
        courseId: [
          {required: true, message: "选择的课程ID不能为空", trigger: "blur"}
        ],
        userName: [
          {required: true, message: "用户账号不能为空", trigger: "blur"}
        ],
        nickName: [
          {required: true, message: "用户昵称不能为空", trigger: "blur"}
        ],
        attendanceType: [
          {required: true, message: "考勤类型不能为空", trigger: "blur"}
        ],
        attendanceTime: [
          {required: true, message: "考勤时长不能为空", trigger: "blur"}
        ],
      },
      endType: 0,
      signCompleted: 0,
      // 新增的扫码签到模态框相关变量
      scanTitle: "考勤情况",
      scanDialogVisible: false,
      timer: null, // 用于存储定时器的变量
      courseRecordId: null, // 动态参数通过路由或接口获取
      baseUrl: null, // 后端获取
      attendanceTypeForScan: null,
    };
  },
  created() {
    this.getList();
    this.getEndType(this.courseId);
    this.getQtCode();
  },
  mounted() {
    // 从后端接口获取考勤数据
    this.getSignRecordList();
    // 启动定时刷新
    // this.startRefresh();
  },
  watch: {
    // 监听模态窗的显示状态
    scanDialogVisible(val) {
      if (val) {
        this.startRefresh(); // 打开时启动刷新
      } else {
        this.stopRefresh(); // 关闭时停止刷新
      }
    }
  },
  computed: {
    qrCodeUrl() {
      const url = `${this.baseUrl}?courseRecordId=${this.courseRecordId}`;
      return url;
    }
  },
  methods: {
    endCourse() {
      this.$modal.confirm('是否结束上课')
        .then(() => {
          // 使用箭头函数，this 指向 Vue 实例
          return endCourseRecord(this.courseId);
        })
        .then(() => {
          // 接口调用成功，显示成功消息
          this.$modal.msgSuccess("已结束上课");
          // 关闭当前 tabs
          this.$store.dispatch("tagsView/delView", this.$route);
          // 路由跳转
          this.$router.go(-1);
        })
        .catch((error) => {
          // 这里只处理真正的错误情况，例如接口调用失败
          if (error instanceof Error) {
            this.$modal.msgError('结束课程上课记录失败:', error);
          }
        });
    },
    openAttendanceDialog() {
      this.reset();
      this.open = true;
      this.title = "发布考勤";
    },
    addAttendence() {
      // 发布考勤选项
      this.$refs["attendanceForm"].validate(valid => {
        if (valid) {
          // 添加 courseId 和 courseName 到 form 对象
          this.attendanceForm.courseId = this.courseId;
          this.attendanceForm.courseName = this.courseName;

          // 提交考勤数据
          addAttendanceRecord(this.attendanceForm).then(response => {
            this.$modal.msgSuccess("考勤发布成功");
            this.getCourseRecordId();
            this.open = false;
            // this.getList();
            this.endType = 0; // 考勤状态只有在页面加载时刷新，因此发布考勤按钮后应显示该查看考勤按钮
          });

        }
      });
    },
    // 获取考勤类型
    getAttendanceType(){
      getAttendanceTypeByCourseId(this.courseId).then(response => {
        this.attendanceTypeForScan = response.data;
      });
    },
    getCourseRecordId(){
      getCourseRecordIdByCourseId(this.courseId).then(response => {
        const timestamp = Date.now().toString();
        const position = 6;
        const combinedData = timestamp.slice(0, position) + response.data + 'i' + timestamp.slice(position);
        this.courseRecordId = combinedData;

      });
    },
    getQtCode(){
      getCodeLink().then(response => {
        this.baseUrl = response.msg;
        this.getCourseRecordId();
      });
    },
    signDetail() {
      // 查看考勤情况
      this.getSignRecordList();
      this.getAttendanceType();
      this.getQtCode();
      // 显示扫码签到模态框
      this.scanDialogVisible = true;
    },
    // 启动定时刷新的方法
    startRefresh() {
      this.timer = setInterval(() => {
        this.getSignRecordList(); // 定时重新获取数据
      }, 3000); // 每隔3秒刷新一次，可根据需求调整时间间隔
    },
    // 停止定时刷新
    stopRefresh() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    getSignRecordList(){
      const data = {
        courseId: this.courseId
      };
      listSignRecordForDetail(data).then(response => {
        this.signRecordList = response.rows;
        this.signCompleted = this.signRecordList.length;
      });
    },
    getEndType(courseId){
      // 0：未结束签到，1：已结束签到
      getEndType(courseId).then(response => {
        this.endType = response.data;
      });
    },
    /** 查询课程学生列表列表 */
    getList() {
      this.loading = true;
      listCourseStudents(this.queryParams, this.courseId).then(response => {
        this.courseStudentsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.scanDialogVisible = false;
      // 关闭对话框时清除定时器
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    // 表单重置
    reset() {
      this.form = {
        courseId: null,
        userName: null,
        nickName: null,
        email: null,
        phonenumber: null,
        sex: null,
        deptName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.userNames = selection.map(item => item.userName)
      this.nickNames = selection.map(item => item.nickName)
      this.userIds = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 退出课程按钮操作 */
    handleDelete(row) {
      const userNames = row.userName || this.userNames;
      const nickNames = row.nickName || this.nickNames;
      let userIds = row.userId || this.userIds;
      if (!Array.isArray(userIds)) {
        userIds = [userIds];
      }
      const courseId = this.courseId;
      this.$modal.confirm('是否退出学工号为"' + userNames + '", 姓名为"'+ nickNames +'"的数据项？').then(function () {

        return delCourseStudents(courseId, userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("退课成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const params = {
        ...this.queryParams,
        courseId: this.courseId
      };
      this.download('course/startCourse/courseStudents/export', params, `《${this.courseName}》学生列表_${new Date().getTime()}.xlsx`);
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  }
};
</script>

<style scoped>
.course-info-page {
  padding: 20px;
}

.course-info-header {
  padding: 10px 20px;
  margin: 0 0 20px;
  border-left: 5px solid #eee;
}

.course-info-header h1 {
  margin: 0;
}

.button-group {
  display: flex;
  gap: 10px; /* 按钮之间的间距 */
}

.scan-dialog-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.title-vertical-line {
  width: 3px;
  height: 20px;
  background-color: #ccc;
  margin-right: 10px;
}

.scan-content {
  margin-bottom: 10px;
}

.content-separator {
  border: none;
  border-top: 1px solid #ccc;
  margin: 10px 0;
}

.attendance-info {
  margin-bottom: 10px;
}
table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}
.qrcode-container {
  padding: 20px;
  text-align: center;
  background: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,.1);
}

.tip-text {
  margin-top: 15px;
  color: #606266;
  font-size: 14px;
}
</style>
